import React, { useState,useEffect } from 'react'
import { Toast,Icon } from 'antd-mobile'
import VirtualizedList from '../../components/VirtualizedList'

import Navbar from '../../components/Navbar'

import { reqCityList,reqCityHot } from '../../api'

import './index.scss'

export default function CityList(props) {

  const {cityName}=props.location.state //首页传过来的当前定位城市

  const [data, setData] = useState(null)

  useEffect(()=>{
    async function getList(params){
      Toast.loading('loading...',0)
      let res=await reqCityList(params)
      let hotRes=await reqCityHot()
      let data={}
      res.body.forEach(i=>{
        let letter=i.short[0].toUpperCase()
        if(!data[letter]){
          data[letter]=[]
        }
        data[letter].push(i)
      })
      let labels=Object.keys(data).sort()
      labels.unshift('hot')
      labels.unshift('#')
      data['hot']=hotRes.body
      data['#']=cityName
      setData({data,labels})
      Toast.hide()
    }
    if(!data)getList({level:1})
  },[data,cityName])

  return (
    <div>
      <div className='city-list-navbar'>
        <Navbar title='城市选择'></Navbar>
      </div>
      <div className='city-list'>
        {
          data?
          <VirtualizedList data={data} history={props.history}></VirtualizedList>:
          <span className='city-list-render-loading'><Icon type='loading'></Icon>数据加载中...</span> 
        }
      </div>
    </div>
  )
}
